<?php

namespace app\admin\controller\shopro\commission;

use think\Db;
use app\admin\controller\shopro\Base;
use addons\shopro\library\commission\Log as LogLibrary;
use addons\shopro\exception\Exception;

/**
 * 代理商管理
 *
 */
class Agents extends Base
{

    // protected $relationSearch = true;


    /**
     * @var \app\admin\model\shopro\commission\Agents
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shopro\commission\Agent;
        $this->userModel = new \app\admin\model\shopro\user\User;
     }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $nobuildfields = ['nickname', 'mobile'];
            list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);

            $total = $this->buildSearch()
                ->where($where)
                ->where('level','in','5,6')
                ->order($sort, $order)
                ->count();

            $list = $this->buildSearch()
                ->with(['user' => function ($query) {
                    return $query->withField('id, avatar, nickname, mobile, child_user_count, child_user_count_1, total_consume');
                }, 'agent_level' => function ($query) {
                    return $query->withField('image, name, level, commission_rules');
                }])
                ->where($where)
                ->where('level','in','5,6')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key=>$value){

                $area_data = \app\admin\model\shopro\Area::where('id',$value['area_id'])->order('id asc')->find();
                $list[$key]['area_level'] = !empty($area_data['level']) ? $area_data['level'] : '';
                $list[$key]['area_name'] = !empty($area_data['name']) ? $area_data['name'] :'';
            }
            $result = array("total" => $total, "rows" => $list);
            $this->success('查看代理商', null, $result);
        }
        return $this->view->fetch();
    }



    /**
     *绑定代理商
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function bindAgent($id)
    {
         $agent = new \addons\shopro\library\commission\Agent($id);
        if (!$agent->agent) {
            $this->error('未找到分销商');
        }
        $data = json_decode($this->request->post('data'),true);
        $agent->agent->area_id = isset($data['area']) ?  $data['area'] : $data['city'];
        $agent->agent->save();
        return $this->success('更新成功', null, $agent->agent);
    }
    /**
     * 选择
     */
    public function select()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $searchWhere = $this->request->request('searchWhere');
            $total = $this->model
                ->where($where)
                ->whereOr('id', '=', $searchWhere)
                ->whereOr('nickname', 'like', "%$searchWhere%")
                ->whereOr('mobile', 'like', "%$searchWhere%")
                ->order($sort, $order)
                ->field('id, nickname, mobile, avatar')
                ->count();
            $list = $this->model
                ->where($where)
                ->whereOr('id', '=', $searchWhere)
                ->whereOr('nickname', 'like', "%$searchWhere%")
                ->whereOr('mobile', 'like', "%$searchWhere%")
                ->order($sort, $order)
                ->field('id, nickname, mobile, avatar')
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            $this->success('选择用户', null, $result);
        }
        return $this->view->fetch();
    }


    /**
     * 分销商搜索
     */
    public function buildSearch()
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter = $filter ? $filter : [];

        $nickname = isset($filter['nickname']) ? $filter['nickname'] : '';
        $mobile = isset($filter['mobile']) ? $filter['mobile'] : '';

        $name = $this->model->getQuery()->getTable();
        $tableName = $name . '.';

        $agents = $this->model;

        if ($nickname || $mobile) {
            $agents = $agents->whereExists(function ($query) use ($nickname, $mobile, $tableName) {
                $userTableName = (new \app\admin\model\User())->getQuery()->getTable();

                $query = $query->table($userTableName)->where($userTableName . '.id=' . $tableName . 'user_id');

                if ($nickname) {
                    $query = $query->where('nickname', 'like', "%{$nickname}%");
                }

                if ($mobile) {
                    $query = $query->where('mobile', 'like', "%{$mobile}%");
                }

                return $query;
            });
        }

        return $agents;
    }



    /**
     * 用户 team 搜索 
     */
    public function buildUserSearch()
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter = $filter ? $filter : [];

        $level = isset($filter['level']) ? $filter['level'] : '';

        $name = $this->userModel->getQuery()->getTable();
        $tableName = $name . '.';

        $users = $this->userModel;

        if ($level) {
            $users = $users->whereExists(function ($query) use ($level, $tableName) {
                $agentTableName = (new \app\admin\model\shopro\commission\Agent())->getQuery()->getTable();

                $query = $query->table($agentTableName)->where($tableName . 'id=' . $agentTableName . '.user_id')
                    ->where('level', $level);

                return $query;
            });
        }

        return $users;
    }


    /**
     * 分销商详情
     */
    public function profile($id)
    {
        $row = $this->model->with(['user' => function ($query) {
            return $query->withField('id, avatar, nickname, mobile, child_user_count, child_user_count_1, child_user_count_2, total_consume');
        }, 'agent_level' => function ($query) {
            return $query->withField('image, name, level, commission_rules');
        }, 'parent_agent' => function ($query) {
            return $query->withField('id, avatar, nickname');
        }])->where('user_id', $id)->find();
        if (!$row) {
            $this->error('未找到分销商');
        }
        $row['area_name'] = db("shopro_area")->where('id',$row['area_id'])->field('name')->find();
        if ($this->request->isAjax()) {
            $this->success('分销商详情', null, $row);
        }
        $this->assign('row',$row);
        $this->assignconfig('row', $row);
        return $this->view->fetch();
    }
}
